package org.example;

import java.util.Arrays;

/**
 * @Auther: wangbw
 * @Date:2020/10/28
 * @Description: org.example
 * @version: 1.0
 */
public class KMPDemo {
    //String abababca
    public static void main(String[] args) {
        String str = "abaababca";
        int[] arr = new int[str.length()];
        getNext(str, arr);
        System.out.println(Arrays.toString(arr));
        String handle = "acdabaababcaca3";
        int i = 0,j = 0;
        while (i < handle.length()  - 1){
            System.out.println("i\t" + i + "\tj\t" + j);
            if(j == -1 || handle.charAt(i) == str.charAt(j)){
                if(j == str.length() - 1){
                    System.out.println(i-j);
                    return;
                }
                i++;
                j++;
            }else {
                j = arr[j];
            }
        }
        System.out.println("NULL");
    }

    static void getNext(String str, int[] next){
        next[0] = -1;
        int i = 0, j = -1;
        while (i < str.length() -1 ){
            if (j == - 1 || str.charAt(i) == str.charAt(j)){
                i++;
                j++;
                next[i] = j;
            }else {
                j = next[j];
            }
        }
    }
}
/**
 * [-1, 0, 0, 1, 2, 3, 4, 0]
 * */
